﻿/*
   Copyright 2011 Oren Nachman

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Threading;

namespace AppLookup
{
    static class BackgroundResolver
    {
        private static Thread _thread;

        /// <summary>
        /// Executes a first web request (on a background thread)
        /// This helps the app do its initial proxy discovery and DNS lookup
        /// hopefully before the user needs to make a real request
        /// </summary>
        /// <param name="domain"></param>
        public static void Do(string domain)
        {
            if (_thread != null && _thread.IsAlive)
                return;

            _thread = new Thread(new ParameterizedThreadStart(ResolverThread));
            _thread.Start(domain);
        }

        private static void ResolverThread(object obj)
        {
            string domain = obj as string;

            if (obj == null)
                return;

            HttpWebRequest request;

            try
            {
                request = (HttpWebRequest)WebRequest.Create("http://" + domain);
                request.GetResponse();
            }
            catch
            {
                // expected, ignore.
            }
        }

        public static void Abort()
        {
            if (_thread != null && _thread.IsAlive)
                _thread.Abort();
        }
    }
}
